﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Configuration;

using FireBus.Contracts;


namespace FireBus.Core.Configuration
{
	public class XmlConfiguration : IConfiguration
	{
		public IMessageAccessor GetMessageAccessor()
		{
			var section = GetSection();
			if (section != null)
			{
				Type type = null;
				try
				{
					type = Type.GetType(section.MessageAccessor);
				}
				catch (TypeLoadException)
				{
				}
				catch (FileLoadException)
				{
				}
				if (type != null)
				{
					var instance = Activator.CreateInstance(type) as IMessageAccessor;
					if (instance != null)
					{
						return instance;
					}
				}
			}
			return new ResourcesMessageAccessor();
		}

		public IList<ExtensionToken> GetExtensionTokens()
		{
			var tokens = new List<ExtensionToken>();
			var section = GetSection();
			if (section != null)
			{
				foreach (ExtensionTokenElement tokenElement in section.Extensions)
				{
					var token = new ExtensionToken(
						tokenElement.Name,
						tokenElement.Path,
						tokenElement.TypeName);
					tokens.Add(token);
				}
			}
			
			return tokens;
		}

		private static HostConfigurationSection GetSection()
		{
			var section = ConfigurationManager.GetSection("host") as HostConfigurationSection;
			return section;
		}
	}
}
